package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.ExcelSubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.context.annotation.Configuration;

/**
 * @author 25169
 */

@Configuration
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {

    public EduSubjectService eduSubjectService;

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext context) {
        if(data==null){
            throw new GuliException(20001,"文件没有内容");
        }
        //一行一行读取，每次读取都有两个值，第一个值一级分类，第二个值二级分类
        //添加一级分类
        EduSubject eduSubject = this.existOneSubject(eduSubjectService, data.getOneSubjectName());
        if(eduSubject==null){
            eduSubject = new EduSubject();
            eduSubject.setTitle(data.getOneSubjectName());
            eduSubject.setParentId("0");
            eduSubjectService.save(eduSubject);
        }

        //添加二级分类
        String id = eduSubject.getId();
        EduSubject eduSubject1 = this.existTwoSubject(eduSubjectService, data.getTwoSubjectName(), id);
        if(eduSubject1==null){
            eduSubject1=new EduSubject();
            eduSubject1.setTitle(data.getTwoSubjectName());
            eduSubject1.setParentId(id);
            eduSubjectService.save(eduSubject1);
        }

    }

    /**
     * //判断二级分类不能重复添加
     * @param subjectService
     * @param name
     * @param pid
     * @return
     */
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid) {
        LambdaQueryWrapper<EduSubject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EduSubject::getTitle,name);
        wrapper.eq(EduSubject::getParentId,pid);
        EduSubject eduSubject = subjectService.getOne(wrapper);
        return eduSubject;
    }

    /**
     * //判断一级分类是否重复
     * @param subjectService
     * @param name
     * @return
     */
    private EduSubject existOneSubject(EduSubjectService subjectService,String name) {
        LambdaQueryWrapper<EduSubject> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EduSubject::getTitle,name);
        wrapper.eq(EduSubject::getParentId,"0");
        EduSubject eduSubject = subjectService.getOne(wrapper);
        return eduSubject;
    }


    /**
     * 读取完成后执行
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
